<?php
$auth = Auth::getAuth('current_user');
$db = new Database();
$fs = new functions();
$userCompany = new userQueries();
$upload = new upload();
$timezone = "Asia/Manila";
if(function_exists('date_default_timezone_set')) date_default_timezone_set($timezone);

    if(isset($_POST['action'])){
    $action = $_POST['action'];
    $date = $fs->currentDateTime();
            
            // Get Contacts
            if($action=="getUsers"){
                $to = $_POST['searchword'];
                $userListID = $_POST['listID'];
                //$splited = explode(",",$userListID); //$contactID = ""; //  //for($a=0;$a<count($splited);$a++){ //    $contactID .= " AND id!=".$splited[$a]; //}
                    $getUser = $db->query("SELECT * FROM tbuser WHERE id!={$db->escape($auth['id'])} AND first_name LIKE '%$to%' AND id NOT IN ($userListID) AND company_id={$db->escape($auth['company_id'])} AND is_active={$db->escape(1)} || id!={$db->escape($auth['id'])} AND  last_name LIKE '%$to%' AND id NOT IN ($userListID) AND company_id={$db->escape($auth['company_id'])} AND is_active={$db->escape(1)} LIMIT 0, 5","array");
                    
                    $encodeUser = array();
                    foreach($getUser as $data){
                        $userID = $data['id'];
                        $re_fname='<b>'.$to.'</b>';
                        $re_lname='<b>'.$to.'</b>';
                        
                            $final_fname = str_ireplace($to, $re_fname, $data['first_name']);
                            $final_lname = str_ireplace($to, $re_lname, $data['last_name']);
                            
                        $user = $final_fname. " " .$final_lname;
                        $images = $userCompany->avatarPic("tbuser",$data['id'],"25","25","small","avatar pull-left");
                        
                        if($data['position']==""){
                            $data = $data['display_name'];
                        }else{
                            $data = $data['position'];
                        }
                        $encodeUser[] = array("userID"      =>  $userID,
                                              "name"        =>  $user,
                                              "img"         =>  $images,
                                              "position"    =>  $data);
                    }
                    echo json_encode($encodeUser);
            }
            
            
            // Create new msg
            elseif($action=="newMsg"){
                $title = $_POST['title'];
                $msg = stripslashes(htmlspecialchars($_POST['msg'],ENT_QUOTES));
                $userListID = $_POST['userListID'];
                
                $images = $_POST['imagesGet'];
                $decode_img = json_decode($images,true);
                // Check if user is in the conversation
                $explode_userListID = explode(",", $userListID);
                if(in_array($auth['id'],$explode_userListID)){
                    $data = $userListID;
                }else{
                    $data = $userListID.",".$auth['id'];
                }
                $q1 = $userListID.",".$auth['id'];
                $q2 = $auth['id'].",".$userListID;                                
                
                $getMsg = $db->query("SELECT * FROM tbmessage WHERE recipient={$db->escape($fs->asortSerializedArray($q2))}","row");
                //$getCount = $db->query("SELECT * FROM tbmessage WHERE recipient={$db->escape($fs->asortSerializedArray($q2))}}","numrows");
                     
                if(!$getMsg){
                    $insert = array("title"             =>      $title,
                                    "message"           =>      $msg,
                                    "senderID"          =>      $auth['id'],
                                    "recipient"         =>      $fs->asortSerializedArray($q2),
                                    "user_read"         =>      0,
                                    "rep"               =>      0,
                                    "date_submit"       =>      $date,
                                    "is_active"         =>      1);
                    $msgID = $db->insert("tbmessage",$insert);
                    $replyInsert = array(   "message_id"    =>  $msgID,
                                            "sender"        =>  $auth['id'],
                                            "message"       =>  $msg,
                                            "reps"          =>  0,
                                            "user_read"     =>  0,
                                            "date_submit"   =>  $date,
                                            "is_active"     =>  1);
                    $reply = $db->insert("tbreply_message",$replyInsert);
                }else{
                    $db->update("tbmessage",array("title"=>$title),array("id"=>$getMsg['id']));
                    
                    $db->update("tbmessage",array("date_submit"=>$date),array("id"=>$getMsg['id']));
                    $msgID = $getMsg['id'];
                    $replyInsert = array(   "message_id"    =>  $getMsg['id'],
                                            "sender"        =>  $auth['id'],
                                            "message"       =>  $msg,
                                            "reps"          =>  0,
                                            "user_read"     =>  0,
                                            "date_submit"   =>  $date,
                                            "is_active"     =>  1);
                    $reply = $db->insert("tbreply_message",$replyInsert);
                }
                
                
                // Seen
                $explode_User = explode(",",$data);
                for($u = 0; $u < count($explode_User); $u++){
                    if($explode_User[$u]==$auth['id']){
                        $read = 1;
                    }else{
                        $read = 0;
                    }
                    $insertSeen = array(   "seen_id"    =>  $reply,
                                            "type"      =>  1,
                                            "userID"    =>  $explode_User[$u],
                                            "date"      =>  $date,
                                            "user_read" =>  $read,
                                            "is_active" =>  1
                                        );
                    $msgSeen = $db->insert("tbseen",$insertSeen);
                }
                
                
                
                // Create folder for the postImage
		    $folder_name = $_POST['folder_location'];
                    $path = "images/" . $folder_name;
                    $id_encrypt = md5(md5($reply));
		    $dir = $path."/".$id_encrypt;
                    if(count($decode_img)!=0){  
                        $upload->createFolder($dir);
                    }
                        // Move files to the directory
                        $copy_foldername = md5(md5($auth['id']));
			$from = "images/" . $folder_name . "/temporaray_files/".$copy_foldername;
                        $postFiles = $upload->getAllfiles_fromDirectory($from);
                            $ext_file = array();
			    $ext_img = array();
                                foreach($decode_img as $img){
                                    copy($from . '/' . $img, $dir . '/' . $img);
				    $extension = explode(".", $img);
				    $last_ext = $extension[count($extension)-1];                                    
				    $valid_formats = unserialize(IMG_EXTENSION);
                                    $path_resize_image = $dir . "/" . $img;
				    
                                    if(!in_array($last_ext,$valid_formats)){
                                        array_push($ext_file,$last_ext);
                                    }else{
                                        array_push($ext_img,$last_ext);
                                    }
                                }
                            $upload->unlinkRecursive($from, "");
                // Audit Logs
                $userCompany->auditLogs($auth,"tbmessage","11",$reply);
                
                $encodePostImage = array("img"              =>  $decode_img,
                                        "postFolderName"    =>  $id_encrypt,
                                        "lengthImg"         =>  count($ext_img),
                                        "extension_file"    =>  $ext_file,
                                        "extension_img"	    =>  $ext_img,
                                        "FolderName" 	    =>  $folder_name,
                                        "image_resize"	    =>	getimagesize($path_resize_image));

//                echo "Message was successfully send.";
                echo header('Content-type: application/json');
                echo json_encode(array(
                    "newMessageId" => $msgID,
                    "attachments" => $encodePostImage
                ));
            }
            
            // Load Extension
            elseif($action=="load_extension"){
                $ret = "";
                $encodeExt = array();
                $userID = $_POST['userID'];
                    $user_split = explode(",",$userID);
                    for($user_split_id=0;$user_split_id<count($user_split);$user_split_id++){
                        $userID = $user_split[$user_split_id];
                        $get_extension = $db->query("SELECT * FROM tbuser WHERE id={$db->escape($userID)} ORDER BY id DESC","array");
                        foreach($get_extension as $ext_info){
                            $encodeExt[] = array("display_name"=>$ext_info['display_name'],
                                                 "length_recipient"=>count($user_split),
                                                 "images"=>$userCompany->avatarPic("tbuser",$ext_info['id'],"35","35","small","avatar pull-left"));
                       }
                    }
                    echo json_encode($encodeExt);
            }
            
                
            // Load Msg
            elseif($action=="loadMsg"){
                if($_POST['type']=="load"){
                    
                   //$getMsg = $db->query("   SELECT *,m.id AS mID, r.id AS replyID
                   //                         FROM tbmessage m
                   //                         LEFT JOIN tbuser u ON u.id = m.senderID
                   //                         LEFT JOIN tbreply_message r ON m.id = r.message_id
                   //                         WHERE m.is_active ={$db->escape(1)}
                   //                         AND u.company_id ={$db->escape($auth['company_id'])}
                   //                         GROUP BY m.id ASC
                   //                         ORDER BY m.id DESC LIMIT 0,10","array");
                    $getMsg = $db->query("  SELECT A.*, r.message, r.sender FROM (SELECT m.*,u.first_name, u.last_name, (SELECT r.id FROM  tbreply_message r WHERE m.id = r.message_id ORDER BY r.Id DESC limit 1 ) AS reply_id
                                            FROM tbmessage m
                                            LEFT JOIN tbuser u ON u.id = m.senderID
                                            WHERE m.is_active ={$db->escape(1)}
                                            AND u.company_id ={$db->escape($auth['company_id'])}
                                            GROUP BY m.id) A
                                            LEFT JOIN tbreply_message r
                                            ON r.id = A.reply_id
                                            ORDER BY A.date_submit DESC LIMIT 10","array");
                                           
                }elseif($_POST['type']=="load_more"){
                    $last_msgID = $_POST['last_msgID'];
                    $getMsg = $db->query("  SELECT A.*, r.message, r.sender FROM (SELECT m.*,u.first_name, u.last_name, (SELECT r.id FROM  tbreply_message r WHERE m.id = r.message_id ORDER BY r.Id DESC limit 1 ) AS reply_id
                                            FROM tbmessage m
                                            LEFT JOIN tbuser u ON u.id = m.senderID
                                            WHERE m.is_active ={$db->escape(1)}
                                            AND 
                                            m.date_submit<{$db->escape($last_msgID)}
                                            AND u.company_id ={$db->escape($auth['company_id'])}
                                            GROUP BY m.id) A
                                            LEFT JOIN tbreply_message r
                                            ON r.id = A.reply_id
                                            ORDER BY A.date_submit DESC LIMIT 5","array");
                }
                    foreach($getMsg as $dataMsg){
                        $msgTitle = $dataMsg['message'];
                        $unread = count($getMsg);
                        $recipient_id = explode(",",$dataMsg['recipient']);
                        
                        
                        // For SEEN VIEW of MSG
                        $getSeen = $db->query("SELECT * FROM tbseen WHERE seen_id={$db->escape($dataMsg['reply_id'])}  AND type={$db->escape(1)} AND is_active={$db->escape(1)}
                                              AND user_read={$db->escape(1)} AND userID={$db->escape($auth['id'])}","numrows");
                        
                        
                        $getUnSeen = $db->query("SELECT * FROM tbseen WHERE seen_id={$db->escape($dataMsg['reply_id'])}  AND type={$db->escape(1)} AND is_active={$db->escape(1)}
                                              AND user_read={$db->escape(0)} AND userID={$db->escape($auth['id'])}","numrows");
                        
                        $getCount = array();
                        for($s = 0; $s<count($recipient_id); $s++){
                                $getCountSeen = $db->query("SELECT * FROM tbseen s
                                                            LEFT JOIN tbuser u on u.id=s.userID
                                                            WHERE s.seen_id={$db->escape($dataMsg['reply_id'])}  AND s.type={$db->escape(1)} AND s.is_active={$db->escape(1)}
                                                            AND s.user_read={$db->escape(1)} AND s.userID={$db->escape($recipient_id[$s])}","row");
                            array_push($getCount,$getCountSeen);
                        }
                        
                        
                        $msgCount = $db->query("SELECT COUNT(DISTINCT r.message_id)  FROM tbseen s
                                 LEFT JOIN tbreply_message r on r.id=s.seen_id
                                 WHERE s.seen_id={$db->escape($dataMsg['reply_id'])} AND s.userID={$db->escape($auth['id'])} AND s.type={$db->escape(1)} AND s.user_read={$db->escape(0)} AND s.is_active={$db->escape(1)}
                                 GROUP BY r.message_id","numrows");
                        
                        // Recipient List
                        $recipient_name = array();
                        $getRecipient = $db->query("SELECT * FROM tbuser WHERE id in(".$dataMsg['recipient'].")","array");
                            foreach($getRecipient as $recipient){
                                $recipient_name[] = array(  "name"    =>  $recipient['first_name']. " " .$recipient['last_name'],
                                                            "userID"  =>  $recipient['id']);
                            }
                        
                                $encodeMsg = array( "msgID"             =>          $dataMsg['id'],
                                                    "replyID"           =>          $dataMsg['reply_id'],
                                                    "title"             =>          $msgTitle,
                                                    "message"           =>          $dataMsg['message'],
                                                    "senderID"          =>          $dataMsg['senderID'],
                                                    "recipient"         =>          $dataMsg['recipient'],
                                                    "recipientCount"    =>          count($recipient_id),
                                                    "unread"            =>          $dataMsg['user_read'],
                                                    "replyCount"        =>          $dataMsg['rep'],
                                                    "date"              =>          $dataMsg['date_submit'],
                                                    "active"            =>          $dataMsg['is_active'],
                                                    "sendBy"            =>          $dataMsg['first_name']. " " .$dataMsg['last_name'],
                                                    "images"            =>          $userCompany->img_avatar_length($dataMsg['recipient'],"tbuser","small",""),
                                                    "no_read"           =>          $unread,
                                                    "recipientName"     =>          $recipient_name,
                                                    "seen"              =>          $getSeen,
                                                    "countSeen"         =>          $getCount,
                                                    "unseen"            =>          $getUnSeen,
                                                    "authName"          =>          $auth['first_name']. " " .$auth['last_name'],
                                                    "messageCount"      =>          $userCompany->countMsg($auth['id']),
                                                    "messageBG"         =>          $msgCount,
                                                    "replySender"       =>          $dataMsg['sender'],
                                                    "authID"            =>          $auth['id']);
                          
                        $arr[] = array("msg"=>$encodeMsg);
                    }
                        
                        echo json_encode($arr);
            }
            
            // Read Msg
            elseif($action=="readMsg"){
                if (array_key_exists('id', $_POST)) {
                    $id = $_POST['id'];
                } else if (array_key_exists('recipients', $_POST)){
                    $recipients = $_POST['recipients'];
                    $query_result = $db->query("SELECT id FROM tbmessage WHERE recipient={$db->escape($fs->asortSerializedArray($recipients))}","row");
                    $id = $query_result['id'];
                } else {
                    //  TODO send message to client that it should provide either id or recipients                    
                }
                   
                $viewMsg = $db->query(" SELECT *, m.id as mID, m.title as msgTitle,
                                        m.user_read as Uread,
                                        m.message as myMessage,
                                        r.id as replyID
                                        FROM tbmessage m
                                        LEFT JOIN tbuser u on u.id=m.senderID
                                        LEFT JOIN tbreply_message r on r.message_id=m.id
                                        WHERE m.id={$db->escape($id)} AND m.is_active={$db->escape(1)} AND u.company_id={$db->escape($auth['company_id'])}","array");
                $insertSeen = "";
                foreach($viewMsg as $dataMsg){
                    // Seen
                    $getMsg = $db->query("SELECT * FROM tbseen WHERE userID={$db->escape($auth['id'])} AND seen_id={$db->escape($dataMsg['replyID'])}","numrows");
                    if($getMsg != 0){
                        $db->update("tbseen",array("user_read"=>1),array("userID"=>$auth['id'],"seen_id"=>$dataMsg['replyID']));
                    }else{
                        $db->insert("tbseen",array("is_active"=>1,"type"=>1,"date"=>$date,"userID"=>$auth['id'],"seen_id"=>$dataMsg['replyID'],"user_read"=>1));
                    }
                    
                    
                    
                    // Recipient List
                    $recipient_name = array();
                    $getRecipient = $db->query("SELECT * FROM tbuser WHERE id in(".$dataMsg['recipient'].")","array");
                    foreach($getRecipient as $recipient){
                        $recipient_name[] = array(  "name"    =>  $recipient['first_name']. " " .$recipient['last_name'],
                                                    "userID"  =>  $recipient['id']);
                    }
                    
                    $encodeViewMsg[] = array(   "msgID"             =>      $dataMsg['mID'],
                                                "title"             =>      $dataMsg['msgTitle'],
                                                "message"           =>      $dataMsg['myMessage'],
                                                "senderID"          =>      $dataMsg['sender'],
                                                "recipient"         =>      $dataMsg['recipient'],
                                                "unread"            =>      $dataMsg['user_read'],
                                                "replyCount"        =>      $dataMsg['rep'],
                                                "date"              =>      $dataMsg['date_submit'],
                                                "active"            =>      $dataMsg['is_active'],
                                                "sendBy"            =>      $dataMsg['first_name']. " " .$dataMsg['last_name'],
                                                "images"            =>      $userCompany->avatarPic("tbuser",$dataMsg['id'],"44","44","small","avatar"),
                                                "no_read"           =>      $dataMsg['Uread'],
                                                "authID"            =>      $auth['id'],
                                                "authName"          =>      $auth['first_name']. " " .$auth['last_name'],
                                                "recipient_name"    =>      $recipient_name);
                }
                
                $fetch_replies_query = "SELECT *,r.id as replyID,r.message_id as msgID, m.title as msgTitle,
                                        m.user_read as Uread,
                                        r.message as myMessage
                                        FROM tbreply_message r
                                        LEFT JOIN tbuser u on u.id=r.sender
                                        LEFT JOIN tbmessage m on m.id=r.message_id
                                        WHERE r.message_id={$db->escape($id)} AND r.is_active={$db->escape(1)} ";
                
                                        //ORDER BY r.id ASC
                
                if (array_key_exists('order', $_POST)) {
                    $fetch_replies_query .= "ORDER BY r.id {$_POST['order']} ";
                } else {
                    $fetch_replies_query .= "ORDER BY r.id ASC ";
                }
                                        
                if (array_key_exists('fetch_limit', $_POST)) {
                    $fetch_replies_query .= "LIMIT {$_POST['fetch_limit']}";
                }
                                        
                // Get Reply message from the database
                $replyMsg = $db->query($fetch_replies_query,"array");
                foreach($replyMsg as $dataMsg){
                    
                    
                    
                    // Load folder for the message
		    $path = "images/messageUpload";
                    $id_encrypt = md5(md5($dataMsg['replyID']));
                    $dir = $path."/".$id_encrypt;
                    $postFiles = $upload->getAllfiles_fromDirectory($dir);
		    
			    $ext_file = array();
			    $ext_img = array();
                                foreach($postFiles as $img){
				    $extension = explode(".", $img);
				    $last_ext = $extension[count($extension)-1];
				    $valid_formats = unserialize(IMG_EXTENSION);
				    $path_resize_image = $dir . "/" . $img;
					if(!in_array($last_ext,$valid_formats)){
					    array_push($ext_file,$last_ext);
					}else{
					    array_push($ext_img,$last_ext);
					}
                                }
				
                    //
                        $encodePostImage = array("img"            =>  $postFiles,
                                               "postFolderName"     =>  $id_encrypt,
                                               "lengthImg"          => count($ext_img),
					       "extension_file"		    =>  $ext_file,
						    "extension_img"		    =>  $ext_img,
                                                    "image_resize"	=>	getimagesize($path_resize_image)
                                               );
                        
                        
                        
                        //for($r_auth_id=0;$r_auth_id<count($recipient_id);$r_auth_id++){
                            $encodeRepMsg[] = array(    "msgID"             =>      $dataMsg['replyID'],
                                                        "conversationID"    =>      $dataMsg['msgID'],
                                                        "title"             =>      $dataMsg['msgTitle'],
                                                        "message"           =>      $dataMsg['myMessage'],
                                                        "senderID"          =>      $dataMsg['sender'],
                                                        "recipient"         =>      $dataMsg['recipient'],
                                                        "unread"            =>      $dataMsg['user_read'],
                                                        "replyCount"        =>      $dataMsg['rep'],
                                                        "date"              =>      $dataMsg['date_submit'],
                                                        "active"            =>      $dataMsg['is_active'],
                                                        "sendBy"            =>      $dataMsg['first_name']. " " .$dataMsg['last_name'],
                                                        "images"            =>      $userCompany->avatarPic("tbuser",$dataMsg['sender'],"44","44","small","avatar"),
                                                        "no_read"           =>      $dataMsg['Uread'],
                                                        "authID"            =>      $auth['id'],
                                                        "authName"          =>      $auth['first_name']. " " .$auth['last_name'],
                                                        "message_attachment"=>      $encodePostImage,
                                                        "recipient_name"    =>      $recipient_name);
                        //}
                }
                // Audit Logs
                $userCompany->auditLogs($auth,"tbmessage","12",$id);
                
                $arr[] = array('msg'=>$encodeViewMsg,'replyMsg'=>$encodeRepMsg);
                echo json_encode($arr);
            }
            
            // Reply Msg
            elseif($action=="replyMsg"){
                $id = $_POST['id'];
                $images = $_POST['imagesGet'];
                $decode_img = json_decode($images,true);
                $addPeopleConversation = $_POST['addPeopleConversation'];
                $msg = stripslashes(htmlspecialchars($_POST['msg'],ENT_QUOTES));
                // Insert to the database
                $insert = array("message_id"=>$id,
                                "sender"=>$auth['id'],
                                "message"=>$msg,
                                "reps"=>0,
                                "user_read"=>0,
                                "date_submit"=>$date,
                                "is_active"=>1);
                
                $replyMsg_id = $db->insert("tbreply_message",$insert);
                
                $db->update("tbmessage",array("date_submit"=>$date),array("id"=>$id));
                
                // Seen
                $explode_User = explode(",",$addPeopleConversation);
                for($u = 0; $u < count($explode_User); $u++){
                    if($explode_User[$u]==$auth['id']){
                        $read = 1;
                    }else{
                        $read = 0;
                    }
                    $insertSeen = array(   "seen_id"   =>  $replyMsg_id,
                                            "type"      =>  1,
                                            "userID"    =>  $explode_User[$u],
                                            "date"      =>  $date,
                                            "user_read" =>  $read,
                                            "is_active" =>  1
                                        );
                    $msgSeen = $db->insert("tbseen",$insertSeen);
                }
                
                
                // Create folder for the postImage
		    $folder_name = $_POST['folder_location'];
                    $path = "images/" . $folder_name;
                    $id_encrypt = md5(md5($replyMsg_id));
		    $dir = $path."/".$id_encrypt;
                    if(count($decode_img)!=0){  
                        $upload->createFolder($dir);
                    }
                        // Move files to the directory
                        $copy_foldername = md5(md5($auth['id']));
			$from = "images/" . $folder_name . "/temporaray_files/".$copy_foldername;
                        $postFiles = $upload->getAllfiles_fromDirectory($from);
                            $ext_file = array();
			    $ext_img = array();
                                foreach($decode_img as $img){
                                    copy($from . '/' . $img, $dir . '/' . $img);
				    $extension = explode(".", $img);
				    $last_ext = $extension[count($extension)-1];
				    $valid_formats = unserialize(IMG_EXTENSION);
				    $path_resize_image = $dir . "/" . $img;
					if(!in_array($last_ext,$valid_formats)){
					    array_push($ext_file,$last_ext);
					}else{
					    array_push($ext_img,$last_ext);
					}
                                }
                            $upload->unlinkRecursive($from, "");
                    
                    // Return        
                    $postImage = $upload->getAllfiles_fromDirectory($dir);
                    
                    // 
                        $encodePostImage = array(   "img"                   =>  $decode_img,
                                                    "postFolderName"        =>  $id_encrypt,
                                                    "lengthImg"             =>  count($ext_img),
						    "extension_file"	    =>  $ext_file,
						    "extension_img"	    =>  $ext_img,
						    "FolderName" 	    =>  $folder_name,
                                                    "image_resize"	    =>	getimagesize($path_resize_image));
                
                
                // json return
                $encodeReply_msg = array(   "conversationID"    =>      $id,
                                            "msgID"             =>      $replyMsg_id,
                                            "title"             =>      "",
                                            "message"           =>      $msg,
                                            "senderID"          =>      $auth['id'],
                                            "recipient"         =>      "",
                                            "unread"            =>      0,
                                            "replyCount"        =>      0,
                                            "date"              =>      $date,
                                            "active"            =>      1,
                                            "sendBy"            =>      $auth['first_name']. " " .$auth['last_name'],
                                            "images"            =>      $userCompany->avatarPic("tbuser",$auth['id'],"44","44","small","avatar"),
                                            "no_read"           =>      "",
                                            "authID"            =>      $auth['id'],
                                            "message_attachment"=>      $encodePostImage);
                
                
                // Audit Logs
                $userCompany->auditLogs($auth,"tbmessage","13",$replyMsg_id);
                
                echo json_encode($encodeReply_msg);
            }
            
            // Delete Message
            elseif($action=="deleteMessage"){
                $id = $_POST['dataID'];
                
                $getMsg = $db->query("SELECT * FROM tbmessage WHERE id={$db->escape($id)}","row");
                $recipient = explode(",",$getMsg['recipient']);
                for($a=0;$a<=count($recipient);$a++){
                    if($recipient[$a]!=$auth['id']){
                        $users .= $recipient[$a] . ",";
                        $users_sub = substr($users, 0, -1);
                        $set = array("recipient"    =>      $users_sub);
                        $condition = array("id"     =>      $id);
                        
                        $db->update("tbmessage",$set,$condition);
                    }
                }
                    
                    // Audit Logs
                    $userCompany->auditLogs($auth,"tbmessage","17",$id);
                    
                    echo "Selected message was successfully deleted.";
            }
            
            // Add People to conversation
            elseif($action=="addPeople"){
                $id = $_POST['dataID'];
                $people = $_POST['people'];
                
                $set = array("recipient"    =>      $people);
                $condition = array("id"     =>      $id);
                
                $db->update("tbmessage",$set,$condition);
                
                // Audit Logs
                    $userCompany->auditLogs($auth,"tbmessage","16",$id);
                
                //// Seen
                //$explode_User = explode(",",$people);
                //for($u = 0; $u < count($explode_User); $u++){
                //    if($explode_User[$u]==$auth['id']){
                //        $read = 0;
                //    }
                //    $insertSeen = array(   "seen_id"   =>  $replyMsg_id,
                //                            "type"      =>  1,
                //                            "userID"    =>  $explode_User[$u],
                //                            "date"      =>  $date,
                //                            "user_read" =>  $read,
                //                            "is_active" =>  1
                //                        );
                //    $msgSeen = $db->insert("tbseen",$insertSeen);
                //}
                
                echo "Successfully added.";
            }
    }


?>